import { Injectable } from '@nestjs/common'
import * as OSS from 'ali-oss'
import * as dayjs from 'dayjs'
import ossConfig from '@/config/oss'

@Injectable()
export class OssService {
  private client: OSS

  constructor() {
    this.client = new OSS(ossConfig)
  }

  async getSignature() {
    const date = new Date()
    date.setDate(date.getDate() + 1)

    const policy = {
      expiration: date.toISOString(),
      conditions: [
        ['content-length-range', 0, 10485760000],
      ],
    }

    const formData = await this.client.calculatePostSignature(policy)
    const host = `http://${ossConfig.bucket}.${ossConfig.region}.aliyuncs.com`

    return {
      expire: dayjs().add(1, 'days').unix().toString(),
      policy: formData.policy,
      signature: formData.Signature,
      accessId: formData.OSSAccessKeyId,
      host,
      dir: 'images/',
    }
  }

  // 文件上传
  async uploadFile(file: Express.Multer.File, folder?: string) {
    const fileExtension = file.originalname.split('.').pop() || 'dat'
    const curDate = Math.floor(Date.now() / 1000)
    const fileFolders = {
      'user': `/images/user/${curDate}.${fileExtension}`,
      'score': `/images/score/${curDate}.${fileExtension}`,
    }
    const fileName = fileFolders[folder as keyof typeof fileFolders] || `/images/${curDate}.${fileExtension}`

    try {
      const result = await this.client.put(fileName, file.buffer, {
        headers: {
          'Content-Type': file.mimetype || 'image/png', // 文件类型
          'Content-Disposition': `inline`, // 图片在浏览器直接显示，并非下载
          'x-oss-meta-Content-Disposition': 'inline',
          'x-oss-meta-content-disposition': 'inline',
          'x-oss-object-acl': 'public-read',
        }
      })

      return {
        data: fileName,
      }
    } catch (error) {
      return {
        code: -1,
        message: '上传失败: ' + error.message
      }
    }
  }
}